﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoUpdate
{
    public partial class WebAPIFrom : Form
    {
        public WebAPIFrom()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) System.Net.HttpWebRequest.Create("https://localhost:5001/api/T_SysUpdate/GetFile/12");
                HttpWebResponse response = (HttpWebResponse) request.GetResponse();
                long totalBytes = response.ContentLength;
                progressBar1.Maximum = (int)totalBytes;
                Stream st = response.GetResponseStream();
                Stream so = new FileStream(Application.StartupPath + "/123.exe",FileMode.Create);
                long totalDownloadByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int) by.Length);
                while (osize >0)
                {
                    totalDownloadByte += osize;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    this.progressBar1.Value = (int) totalDownloadByte;
                    osize = st.Read(by, 0, (int) by.Length);
                }
                so.Close();
                st.Close();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.ShowDialog();
                FileInfo fileInfo = new FileInfo(openFileDialog1.FileName);
                
                FileVersionInfo file = FileVersionInfo.GetVersionInfo(openFileDialog1.FileName);
                this.textBox1.Text = file.FileVersion;
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (Process process in Process.GetProcesses())
            {
                if (process.ProcessName.ToUpper().Contains("INVOICEINTERFACE"))
                {
                    process.Kill();
                    process.WaitForExit();
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Process p = new Process();
            p.StartInfo.FileName = @"F:\电子发票\InvoiceInterface\InvoiceInterface\InvoiceInterface\bin\Debug\invoiceinterface.exe";
            p.Start();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            openFileDialog2.ShowDialog();
            try
            {
                HttpClient client = new HttpClient();
                var postContent = new MultipartFormDataContent();
                string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
                postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
                string image_file_Type = "file";
                postContent.Add(new ByteArrayContent(File.ReadAllBytes(openFileDialog2.FileName)), image_file_Type, openFileDialog2.SafeFileName);
                postContent.Add(new StringContent("3"), "FOrder");
                postContent.Add(new StringContent("3"), "FID");
                postContent.Add(new StringContent(openFileDialog2.SafeFileName), "FMemo");
                HttpResponseMessage response = client.PostAsync("http://localhost:5000/api/t_sysupdate/create", postContent).Result;
                string str = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(str);
                // var values = new NameValueCollection()
                // {
                //     {"FOrder","2"},
                //     {"FID","2"},
                //     {"FMemo",openFileDialog2.SafeFileName}
                // };
                //
                // string s = HttpPostData("http://localhost:5000/api/t_sysupdate/Create", 999999, "file", openFileDialog2.FileName, values);
                // Console.WriteLine(s);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
        public string HttpPostData(string url, int timeOut, string fileKeyName,
                                            string filePath, NameValueCollection stringDict)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "--------------------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = new byte[1024];
            int bytesRead; // =0

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }

            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";

            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                             select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);

            webRequest.ContentLength = memStream.Length;

            var requestStream = webRequest.GetRequestStream();

            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }

            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Base64StringToImage(this.richTextBox1.Text);
        }

        public void Base64StringToImage(string strbase64)
        {

            try
            {
                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                System.Drawing.Image img = System.Drawing.Image.FromStream(ms);


                // string ls_path = Server.MapPath(@"images\camera\" + ls_imageNameCamera + ".jpg");

                // img.Save(ls_path, System.Drawing.Imaging.ImageFormat.Jpeg);
                this.pictureBox1.Image = img;
                //System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                //img.Save("ImgName.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //img.Save("ImgName.bmp", ImageFormat.Bmp);
                //img.Save("ImgName.gif", ImageFormat.Gif);
                //img.Save(@"images\ImgName.png", ImageFormat.Png);

            }
            catch (Exception ex)
            {

            }
        }

    }
}
